#!/usr/bin/env python
# encoding: utf-8

"""
@author: liuxiandong
@contact: liuxiandong@37.com
@file: util.py
@time: 2021/3/15 14:49
@desc:
"""
import os
import configparser
import xlsxwriter
import json
from performance import tests
from performance.excel_style import *

curr_dir = os.path.dirname(os.path.realpath(__file__))
root_dir = curr_dir + os.sep + 'excelConfig.ini'

# 实例化config
config = configparser.ConfigParser()
config.read(root_dir, encoding='utf8')


def insert_data_2_excel(data):
    if data is None:
        return
    wk = xlsxwriter.Workbook("测试报告.xlsx")
    workbook_sheet_total = wk.add_worksheet("测试报告")
    workbook_sheet_data = wk.add_worksheet("测试数据")
    _header_style = wk.add_format(header_style)
    _summarize_label_style = wk.add_format(summarize_label_style)
    _test_header_style = wk.add_format(test_header_style)
    _tset_detail_style = wk.add_format(tset_detail_style)
    _test_font_style = wk.add_format(test_font_style)
    workbook_sheet_total.set_row(0, 45)
    workbook_sheet_total.set_row(1, 45)
    workbook_sheet_total.set_row(2, 45)
    workbook_sheet_total.set_column(2, 2, 12)
    workbook_sheet_total.set_row(3, 25)
    workbook_sheet_total.set_row(8, 25)
    workbook_sheet_total.set_row(11, 25)
    header = {}
    count = 1
    title_list = []
    for key, val in data.items():
        # key=id=13    val=FPS
        for val_key, child_val in val.items():
            # val_key = data
            # 正式遍历性能数据'Memory':{}
            for child_val_key, data_val in child_val.items():
                if not isinstance(data_val, dict):
                    break
                for grandchild_key, grandchild_val in data_val.items():
                    # 去掉空数据列
                    if len(grandchild_val) == 0:
                        continue
                    header[key + '_' + child_val_key + grandchild_key] = grandchild_val
                    title_list.append(key + '_' + child_val_key + grandchild_key)
                    workbook_sheet_data.merge_range(1, count - 1, 1, count, key + '_' + grandchild_key)
                    workbook_sheet_data.write(2, count - 1, '时间')
                    workbook_sheet_data.write(2, count, '值')
                    for i in range(len(grandchild_val)):
                        workbook_sheet_data.write(i + 2, count - 1, i + 1)
                        # if grandchild_val[i]['b'] == '0.0':
                        #     continue
                        workbook_sheet_data.write(i + 2, count, grandchild_val[i]['b'])
                    count += 2
    count1 = 0
    init_num = 13
    # jank_count = 0
    average_fps = []
    average_cpu = []
    average_mem = []
    data_list = []
    y_value = []
    categories = []
    _value = []
    # print(header)
    for title_key, value in header.items():
        # value为数据行数
        _value.append((title_key, len(value)))
        if len(value) == 0:
            continue
        elif '帧率' in title_key:
            average_fps.append(caculate_average(value)[1])
        elif '应用进程-main' in title_key:
            average_cpu.append(caculate_average(value)[1])
        elif 'PSS内存-main' in title_key:
            average_mem.append(caculate_average(value)[1])
    # print(_value)
    for i in range(len(_value)):
        if _value[i][1] == 0:
            continue
        categories.append(_value[i][0])
        categories.append("测试数据")
        y_value.append(_value[i][0])
        y_value.append("测试数据")
        categories.append(2)
        categories.append(count1)
        categories.append(_value[i][1] + 1)
        categories.append(count1)
        y_value.append(2)
        y_value.append(count1 + 1)
        y_value.append(_value[i][1] + 1)
        y_value.append(count1 + 1)
        count1 += 2
        # chart.set_x_axis({'name': x_axis})
        # chart.set_y_axis({'name': y_axis})
    for i in range(0, len(y_value), 6):
        if '_Memory全局占用' in y_value[i]:
            print(y_value[i+1:i + 6])
            chart = wk.add_chart({'type': 'line'})
            chart.set_title({'name': "总内存大小情况"})
            chart.add_series({
                'name':y_value[i],
                # 'marker': {'type': 'diamond'},
                'categories': categories[i+1:i + 6],
                'values': y_value[i+1:i + 6],
                # 'line': {'color': 'red'}
            })
            workbook_sheet_total.insert_chart(init_num, 0, chart)
            init_num += 15
        elif 'MemoryPSS内存' in y_value[i]:
            chart = wk.add_chart({'type': 'line'})
            chart.set_title({'name': "进程内存大小情况"})
            chart.add_series({
                'name': y_value[i],
                # 'marker': {'type': 'diamond'},
                'categories': categories[i + 1:i + 6],
                'values': y_value[i + 1:i + 6],
                # 'line': {'color': 'red'}
            })
            workbook_sheet_total.insert_chart(init_num, 0, chart)
            init_num += 15
        elif 'CPU全局占用' in y_value[i]:
            chart = wk.add_chart({'type': 'line'})
            chart.set_title({'name': "总CPU占用情况"})
            chart.add_series({
                'name': y_value[i],
                # 'marker': {'type': 'diamond'},
                'categories': categories[i + 1:i + 6],
                'values': y_value[i + 1:i + 6],
                # 'line': {'color': 'red'}
            })
            workbook_sheet_total.insert_chart(init_num, 0, chart)
            init_num += 15
        elif 'CPU应用进程' in y_value[i]:
            chart = wk.add_chart({'type': 'line'})
            chart.set_title({'name': "进程CPU占用情况"})
            chart.add_series({
                'name': y_value[i],
                # 'marker': {'type': 'diamond'},
                'categories': categories[i + 1:i + 6],
                'values': y_value[i + 1:i + 6],
                # 'line': {'color': 'red'}
            })
            workbook_sheet_total.insert_chart(init_num, 0, chart)
            init_num += 15
        elif '帧率' in y_value[i]:
            chart = wk.add_chart({'type': 'line'})
            chart.set_title({'name': "游戏帧率情况"})
            chart.add_series({
                'name': y_value[i],
                # 'marker': {'type': 'diamond'},
                'categories': categories[i + 1:i + 6],
                'values': y_value[i + 1:i + 6],
                # 'line': {'color': 'red'}
            })
            workbook_sheet_total.insert_chart(init_num, 0, chart)
            init_num += 15

    workbook_sheet_total.merge_range(0, 0, 0, 13, config.get('context', 'title'), _header_style)
    workbook_sheet_total.write(1, 0, config.get('context', 'project_label'), _summarize_label_style)
    workbook_sheet_total.write(1, 3, config.get('context', 'client_package_label'), _summarize_label_style)
    workbook_sheet_total.write(1, 6, config.get('context', 'test_devices_label'), _summarize_label_style)
    workbook_sheet_total.write(1, 10, config.get('context', 'link_data_label'), _summarize_label_style)
    workbook_sheet_total.write(2, 0, config.get('context', 'test_tools'), _summarize_label_style)
    workbook_sheet_total.merge_range(2, 1, 2, 2, config.get('context', 'tools'), _summarize_label_style)
    workbook_sheet_total.write(2, 3, config.get('context', 'server_version'), _summarize_label_style)
    workbook_sheet_total.write(2, 6, config.get('context', 'test_scope'), _summarize_label_style)
    workbook_sheet_total.write(2, 10, config.get('context', 'performance_parameter'), _summarize_label_style)
    workbook_sheet_total.merge_range(3, 0, 3, 13, config.get('context', 'test_conclusion_label'), _test_header_style)
    workbook_sheet_total.write(4, 0, config.get('context', 'serial_number'), _tset_detail_style)
    workbook_sheet_total.merge_range(4, 1, 4, 13, config.get('context', 'detail_label'), _tset_detail_style)
    workbook_sheet_total.write(5, 0, '1')
    workbook_sheet_total.merge_range(5, 1, 5, 13, '平均内存大小分别为%s' % str(average_mem).strip('[]') + 'M')
    workbook_sheet_total.write(6, 0, '2')
    workbook_sheet_total.merge_range(6, 1, 6, 13, '平均帧率大小分别为%s' % str(average_fps).strip('[]'))
    workbook_sheet_total.write(7, 0, '3')
    workbook_sheet_total.merge_range(7, 1, 7, 13, '平均CPU占用大小分别为%s' % str(average_cpu).strip('[]'))
    workbook_sheet_total.merge_range(8, 0, 8, 13, config.get('context', 'test_issue'), _test_header_style)
    workbook_sheet_total.write(9, 0, config.get('context', 'serial_number'), _tset_detail_style)
    workbook_sheet_total.merge_range(9, 1, 9, 13, config.get('context', 'detail_label'), _tset_detail_style)
    workbook_sheet_total.write(10, 0, ' ')
    workbook_sheet_total.merge_range(10, 1, 10, 13, '建议根据下面图的一些拐点（或者）数值比较大（针对内存，CPU）（fps较小）的情况进行说明',
                                     _test_font_style)
    workbook_sheet_total.merge_range(11, 0, 11, 13, config.get('context', 'test_chart'), _test_header_style)
    wk.close()
    data_list.append(str(average_mem).strip('[]'))
    data_list.append(str(average_fps).strip('[]'))
    data_list.append(str(average_cpu).strip('[]'))
    # data_list.append(max_delay_time)
    # data_list.append(jank_count)
    return data_list


def caculate_average(value):
    # average = 0
    average_data = []
    for i in range(len(value)):
        if value[i]['b'] == '0.0':
            break
        average_data.append(value[i]['b'])
    average = round(sum(average_data) / len(average_data), 2)
    return average_data, average


if __name__ == '__main__':
    insert_data_2_excel(tests.data)
    # curr_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    # root_dir = curr_dir + os.sep + 'templates\emailreport.html'
    # print(root_dir)
    # list = ['15_Memory全局占用', '测试数据', 2, 1, 10, 1, '15_MemoryPSS内存-main-2498', '测试数据', 2, 3, 10, 3,
    #         '15_MemoryPrivateDirty内存-main-2498', '测试数据', 2, 5, 10, 5, '15_FPS（游戏）帧率', '测试数据', 2, 7, 11, 7,
    #         '15_FPS（游戏）延迟次数', '测试数据', 2, 9, 11, 9, '15_FPS（游戏）最长延迟时间', '测试数据', 2, 11, 11, 11, '15_CPU全局占用', '测试数据', 2,
    #         13, 20, 13, '15_CPU应用进程-main-2498', '测试数据', 2, 15, 20, 15, '19_Memory全局占用', '测试数据', 2, 17, 7, 17,
    #         '19_MemoryPSS内存-main-2498', '测试数据', 2, 19, 7, 19, '19_MemoryPrivateDirty内存-main-2498', '测试数据', 2, 21, 7, 21,
    #         '19_FPS（游戏）帧率', '测试数据', 2, 23, 8, 23, '19_FPS（游戏）延迟次数', '测试数据', 2, 25, 8, 25, '19_FPS（游戏）最长延迟时间', '测试数据', 2,
    #         27, 8, 27, '19_CPU全局占用', '测试数据', 2, 29, 15, 29, '19_CPU应用进程-main-2498', '测试数据', 2, 31, 15, 31]
    # # list = [1,2,3,4,5,6,7,8,9,4,2,3,5,2,6]
    # for i in range(0,len(list),6):
    #     print(list[i]+':'+str(list[i+1:i+5]))
